package com._520it.crm.util;
//用户修改密码时的Servlet后台处理实现

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

//记住要引入自己定义的这两个类

public class Change_Password extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //还是调用写好的doPost方法
        doPost(request,response);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //设置文本格式
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

        //获取用户输入信息
        String username = request.getParameter("Username");
        String old_password = request.getParameter("Password");
        String new_password = request.getParameter("Confirm_Password");


        //获取输出流
        PrintWriter out = response.getWriter();

        /*
        if(old_password.equals(new_password)){
            out.print("<html>");
            out.print("<head></head>");
            out.print("<body>新密码不可与旧密码一致！</body>");
            out.print("</html>");
        }
        */

        //创建链接对象
        Connect connect = new Connect();
        //设置链接字符串（因为链接字符串大多时候不一样，所以我只能把它放在外面）
        String sqlstr = "select * from employee where username='" + username
                + "' and password='" + old_password + "'";
        //调用sqlstr属性的封装函数设置connect对象的属性值
        connect.setSqlstr(sqlstr);
        //设置记录搜索到记录数的变量
        int totalRows = 0;
        try {
            //调用connect中写好的方法，进行查询
            totalRows = connect.excute_query();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (totalRows > 0) {

            //当数据库中有这个人时，我才允许你修改密码
            sqlstr = "update employee set password='" + new_password + "' where username='" + username + "'";
            connect.setSqlstr(sqlstr);
            try {
                //调用connect的另一个方法，更新该记录的密码属性值
                connect.excute_update();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //更新后提示用户，已经修改完成
            out.print("<html>");
            out.print("<head></head>");
            out.print("<body>修改成功！</body>");
            out.print("</html>");
            //给个返回的超链接吧
        } else {
            //如果没有这个人，需要让他先去申请一个账号
            out.print("<html>");
            out.print("<head></head>");
            out.print("<body>账号或密码错误！</body>");
            out.print("</html>");
            //给个超链接跳到注册页面
        }
    }
}
